<?php
/**
* Engine main (static) class. Perform initialization, read/filter GET and POST, load Configuration...
*
* <ul>
* <li>The Core class is the main reference point for many Engine functionalities. It is responsible
* for reading securely all the input variables by filtering out any dangerous inputs or spam
* attempts and such.</li>
* <li>It also manages the URI/URL by parsing the calling URL into parts and reading/fixing the current
* working directory. This is important during the shutdown stage when the CWD can be messed up
* by Apache or other webservers.</li>
* <li>It also reads and parse the configuration variables</li>
* <li>It also abstract access to the client Javascript counterpart by offering standard interfaces for
* Javascript code/scripts add. This is required since the underlying output mechanism can be different
* when the Engine is called in response to a AJAX Request or a direct page:
* <b>Core::JsAddCode</b> -> Adds some Javascript code to the client interface
* <b>Core::JsAddScript</b> -> Adds some Javascript scripts to the client interface</li>
*<li>Last, the E class offer a unified interface for cookie management.</li>
*</ul>
*@package Core
*@subpackage Internals
*@author Willy Gardiol <willy@gardiol.org>
*@version 1.0
*/
class Core extends BaseClassStatic
{
	/**#@+
	* This is part of the internal Engine state and initialization routine
	*@access private
	*/
	/**
	* Engine initialization routine
	*
	* This actually initialize most of the Engine:
	* <ol>
	* <li>Setup URI (path+base)</li>
	* <li>Read, parse and filter GET and POST parameters</li>
	* <li>Store the CWD at startup time for later fixing on shutdown</li>
	* <li>Read configuration variables from <i>Engine/config.php</i></li>
	* </ol>
	*/
	static public function Initialize()
	{	# Do not init more than once...
		static $already_init = 0;
		if ( ($already_init++)>0 )
			throw new Exception("Engine has already been initialized");

		# Store Current Working Directory
		Core::$cwd = getcwd();
		# Read configuration variables
		require_once BASEPATH."../Config/config.php";
		foreach ( Core::$config["main"] as $key => $default )
			if ( isset( $$key ) )
				Core::$config["main"][ $key ] = $$key;

		# Start session...
		session_name( Core::$config["main"]["session_name"] );
			if ( session_id() == "") session_start();

		# Lets set the timezone, it is better to do this in PHP5+ (not needed but harmless in PHP4)
		ini_set( 'date.timezone', Core::GetConfig("timezone") );
		# This is required for some image managing functions later on (set to external config file?)
		ini_set("memory_limit","250M");
		# Set session timeout
		ini_set("session.gc_maxlifetime", 60*60);
		# Setup zip compression if supported by the browser
		ini_set("zlib.output_compression","on");

		# init URI
		$uri = preg_split( "/(\/*.*\/)(.*?)(\.php)?(\??.*$)/",$_SERVER["REQUEST_URI"], -1,
																	PREG_SPLIT_DELIM_CAPTURE );
		Core::$uri["path"] = ( isset($uri[1]) ) ? $uri[1] : "/";
		Core::$uri["base"] = ( isset($uri[2]) &&  ($uri[2]!="") ) ? $uri[2] : "main";

		# init GET and POST parameters
		Core::$get_vars = new CoreParametersGet();
		Core::$post_vars = new CoreParameters("post");

		# Initialize the CoreAuth (login)...
		CoreAuth::Initialize();
	}

	static private $config = array( "main" => array(
							"error_debug" => false,
							"webmaster" => "please_set@the_webmaster_emain.address",
							"session_name" => "default",
							"description" => "Please set a description!",
							"keywords" => "keywords_needs_to_be_specified",
							"domain" =>"www.please_set_domain.unk",
							"title" => "Please set a title",
							"timezone" => "UTC",
							"lang" => "en",
							"boxes" => array()
							));

	static private $uri=false;
	static private $cwd = false;
	static private $get_vars = false;
	static private $post_vars = false;
	static private $js_scripts = array();
	static private $js_code = array();
	static private $title = "";
	/**#@-*/


	/**
	* Return the parse URI.
	*
	* @param string $w What to read. Can be either <i>path</i> or <i>base</i>
	* @return string The requested portion of the URI
	*/
	static public function GetUri( $w = "path" )
	{
		return Core::$uri[$w];
	}

	/**
	* Reset the Current Working Directory to the default startup-time one.
	*
	* This is required when, during shutdown phase, some web servers do change it and so
	* class descructors and shutdown code will break.
	*/
	static public function FixCwd()
	{
		if ( Core::$cwd && (getcwd() != Core::$cwd) )
			chdir( Core::$cwd );
	}

	/**
	* Read a GET variable
	*
	* @param string $name The name of the variable to read
	* @param mixed $default a required default value to set if $name is not set
	* @param string $type Can either be "string", "bool" or "serialized"
	* @return mixed the requested parameter or the default value if it is not set.
	* Return a GET parameter name $name, or the $default value if GET $name is not defined. Please check
	* {@see Parameters::GetParam()} for more details.
	*/
	static public function GetVar( $name, $default, $type )
	{
		return Core::$get_vars->GetParam( $name, $default, $type );
	}
	static public function RegisterGetVar( $name )
	{
		Core::$get_vars->RegisterVar( $name );
	}
	static public function GenerateGetString( $arr )
	{
		return Core::$get_vars->GenerateString( $arr );
	}

	/**
	* Read a POST variable
	*
	* @param string $name The name of the variable to read
	* @param mixed $default a required default value to set if $name is not set
	* @param string $type Can either be "string", "bool" or "serialized"
	* @return mixed the requested parameter or the default value if it is not set.
	* Return a POST parameter name $name, or the $default value if POST $name is not defined. Please check
	* {@see Parameters::GetParam()} for more details.
	*/
	static public function PostVar( $name, $default, $type )
	{
		return Core::$post_vars->GetParam( $name, $default, $type );
	}

	static public function GetReqId()
	{
		return Core::$get_vars->GetReqId();
	}
	static public function GetDump()
	{
		return Core::$get_vars ? Core::$get_vars->Dump() : array();
	}
	static public function PostDump()
	{
		return Core::$post_vars ? Core::$post_vars->Dump()  :array();
	}

# Config support
	static public function GetConfig($var, $box = "main")
	{
		if ( isset( Core::$config[$box] ) && isset( Core::$config[$box][$var] ) )
			return Core::$config[$box][$var];
		return false;
	}

	static public function LoadExtraConfig( $box )
	{
		if ( isset( Core::$config[$box] ) )
			return false;
		$filename = "Config/config_$box.php";
		if ( file_exists( $filename ) )
		{
			require_once $filename;
			Core::$config[$box] = $config;
			return true;
		}
		return false;
	}

# Page support
	static public function AppendTitle( $title )
	{
		Core::$title .= (Core::$title != "" ? " - " : "").$title;
	}
	static public function GetTitle()
	{
		return Core::$title;
	}
/*	static public function AddJsScript( $plugin_type, $plugin_name, $script )
	{
		switch ($plugin_type)
		{
		case "box":
			$path = "Engine/plugins/Box/$plugin_name/$script";
			break;

		default:
			$path = false;
		}
		if ( $path )
			Core::$js_scripts[] = $path;
	}
	static public function GetJsScripts()
	{
		return Core::$js_scripts;
	}
	static public function AddJsCode( $code )
	{
		Core::$js_code[] = $code;
	}
	static public function GetJsCode()
	{
		return Core::$js_code;
	}*/

# Cookies management...
	static public function GetCookie( $name, $default, $type = "string" )
	{
		return Engine::read_var( $_COOKIE, $name, $default, $type );
	}
	static public function SetCookie( $name, $value, $time = 0 )
	{
		setcookie($name, $value, $time);
	}
	static public function DeleteCookie( $name )
	{
		setcookie($name, "", time() - 3600);
	}

	static public function FilePath( $file, $type = "xxx", $extra = "" )
	{
		if ( $type === "Box" )
			$mid = "plugins/Box/$extra/";
		else if ( $type === "Brick" )
			$mid = "plugins/Brick/$extra/";
		else if ( $type === "Smarty" )
			$mid = "plugins/Smarty/";
		else
			throw new Exception("Invalid type: '$type'");
		return BASEPATH."$mid./$file";
	}

}
?>